package cn.school.demo.util

import java.security.SecureRandom
import java.security.cert.CertificateException
import java.security.cert.X509Certificate
import javax.net.ssl.*

/*
  信任任何站点，实现https页面的正常访问
 */
class HttpsUtil {
    fun trustEveryone() {
        try {
            HttpsURLConnection.setDefaultHostnameVerifier(object : HostnameVerifier {
                override fun verify(hostname: String?, session: SSLSession?): Boolean {
                    return true
                }
            })
            val context: SSLContext = SSLContext.getInstance("TLS")
            context.init(null, arrayOf<X509TrustManager>(object : X509TrustManager {
                @Throws(CertificateException::class)
                override fun checkClientTrusted(
                    chain: Array<X509Certificate?>?,
                    authType: String?
                ) {
                }

                @Throws(CertificateException::class)
                override fun checkServerTrusted(
                    chain: Array<X509Certificate?>?,
                    authType: String?
                ) {
                }

                override fun getAcceptedIssuers(): Array<X509Certificate> {
                    TODO("Not yet implemented")
                }

                val acceptedIssuers: Array<Any?>?
                    get() = arrayOfNulls(0)
            }), SecureRandom())
            HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory())
        } catch (e: Exception) {
            // e.printStackTrace();
        }
    }

}